package com.telit.firecommand.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.telit.common.entity.DataReturn;
import com.telit.common.entity.PageData;
import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.common.util.GeoUtils;
import com.telit.common.util.JwtTokenUtils;
import com.telit.dispose.feign.RemoteDisposeService;
import com.telit.dispose.vo.dispose.PlatTableVO;
import com.telit.firecommand.constant.FireConstant;
import com.telit.firecommand.dao.*;
import com.telit.firecommand.dto.FireSituationListDTO;
import com.telit.firecommand.dto.ForesterDTO;
import com.telit.firecommand.entity.CommAlarmRescue;
import com.telit.firecommand.entity.FireGrowExtend;
import com.telit.firecommand.enums.FireSourceTypeStatus;
import com.telit.firecommand.service.CameraInfoService;
import com.telit.firecommand.service.FireSituationService;
import com.telit.firecommand.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * Create by Chencf 2022/9/22
 */
@Service
@Transactional
public class FireSituationServiceImpl implements FireSituationService {

    @Autowired
    private RemoteDisposeService disposeFeignClient;

//    @Autowired
//    private RemoteUavService uavFeignClient;

    @Autowired
    private CameraInfoService cameraInfoService;

    @Autowired
    private ForesterService foresterService;

    @Autowired
    private FireAlarmsDao fireAlarmsDao;

    @Autowired
    private CommAlarmRescueDao commAlarmRescueDao;

    @Autowired
    private GeoXzqhCunDao geoXzqhCunDao;

    @Autowired
    private FireQueryDao fireQueryDao;
    @Autowired
    private FireGrowExtendDao fireGrowExtendDao;





    @Override
    public Object queryFireSituationByCondition(FireSituationListDTO fireSituationListDTO) {
        if (StringUtils.isNotBlank(fireSituationListDTO.getDistrictCode())){
            fireSituationListDTO.setDistrictCode(fireSituationListDTO.getDistrictCode()+"%");
        }
        IPage<FireQuerySituationAllListVO> commHistorySimpFireVOIPage = new Page<>(fireSituationListDTO.getPage(), fireSituationListDTO.getRows());
        IPage<FireQuerySituationAllListVO> pages = fireQueryDao.queryFireSituationByCondition(commHistorySimpFireVOIPage,  fireSituationListDTO);
        List<FireQuerySituationAllListVO> records = pages.getRecords();


        for (FireQuerySituationAllListVO fireQueryAllListVO:records){
            //根据行政区划代码查询地址
            if (fireQueryAllListVO.getDistrictCode()!= null) {
                fireQueryAllListVO.setDistrictCodeName(geoXzqhCunDao.queryNameByCode(fireQueryAllListVO.getDistrictCode(),fireQueryAllListVO.getDistrictCode().length()));
            }
            if (StringUtils.isNotBlank(fireQueryAllListVO.getSourceType())){
                fireQueryAllListVO.setSourceTypeName( FireSourceTypeStatus.code2Str(Integer.parseInt(fireQueryAllListVO.getSourceType())));
            }

        }
        pages.setRecords(records);
        PageData<Object> pageData = new PageData<>();
        pageData.setDatas(pages.getRecords());
        pageData.setCount((int) pages.getTotal());
        pageData.setCurrent((int) pages.getCurrent());
        pageData.setSize((int) pages.getSize());
        return pageData;

    }

    //判断是否可以点击启动响应按钮
    @Override
    @Transactional
    public Boolean isOkRescue(String districtCode, String fireId) {
        Boolean flag = true;
        FireGrowExtend fireGrowExtend = fireGrowExtendDao.selectByFireId(fireId);
        //拿到可以处理的行政区划code
        if (Objects.nonNull(fireGrowExtend)&&!districtCode.equals(fireGrowExtend.getDistrictCode())){
            flag=false;
        }
        if (flag){
            Integer rescue = fireAlarmsDao.isRescue(fireId);
            if (rescue!=0) {
                CommAlarmRescue commAlarmRescue = new CommAlarmRescue();
                commAlarmRescue.setFireId(fireId);
                commAlarmRescue.setDistrictCode(districtCode);
                commAlarmRescue.setCreateTime(new Date());
                commAlarmRescueDao.insertSelective(commAlarmRescue);
            }
        }
        return flag;
    }


    @Override
    public CommAlarmRescueVO releaseRescue(String districtCode, String fireId) {
        CommAlarmRescueVO commAlarmRescueVO = new CommAlarmRescueVO();
        commAlarmRescueVO.setFlag(true);
        QueryWrapper<CommAlarmRescue> wrapper = new QueryWrapper<>();
        wrapper.eq("fire_id", fireId);
        CommAlarmRescue commAlarmRescue = commAlarmRescueDao.selectOne(wrapper);
        if (Objects.nonNull(commAlarmRescue)) {
            if (commAlarmRescue.getDistrictCode().equals(districtCode)) {
                commAlarmRescueVO.setMsg("");
                commAlarmRescueVO.setFlag(true);
            } else {
                //查询哪一级开始扑救的
                String districtCodeName = geoXzqhCunDao.queryNameByCode(commAlarmRescue.getDistrictCode(),
                        commAlarmRescue.getDistrictCode().length());
                commAlarmRescueVO.setMsg("该火情" + districtCodeName + "正在扑救中");
                commAlarmRescueVO.setFlag(false);
            }
        }
        if (commAlarmRescueVO.getFlag()) {
            QueryWrapper<CommAlarmRescue> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("fire_id", fireId);
            commAlarmRescueDao.delete(deleteWrapper);
        }
        return commAlarmRescueVO;
    }

    /**
     * 火场态势周围资源查询
     *
     * @param longitude
     * @param latitude
     * @param radius
     *
     * @return
     */
    @Override
    public Map<String, List<FireSituationVO>> getSimpleGeoSourceNearbyRadius(String longitude, String latitude,
                                                                             String radius, String flag,
                                                                             String districtCode) {
        Map<String, List<FireSituationVO>> resultMap = new HashMap<>();
        //查询对应表plat_meta_table表里为  防火资源数据
        List<PlatTableVO> platTableVOList;
        DataReturn allTableData = disposeFeignClient.selectAllTable(flag);
        if (!ResultCode.SUCCESS.getCode().equals(allTableData.getCode())
                && !FireConstant.ALARMS_SUCCESS_CODE.equals(allTableData.getCode())) {
            throw new ForestBaseException(allTableData.getErrorMsg());
        }
        //拿到所有的原始表信息 包括表的名称，表的描述（表名称汉字）
        platTableVOList = JSON.parseArray(JSON.toJSONString(allTableData.getData()), PlatTableVO.class);

        //将表的名称拿到
        String tableNames = platTableVOList.stream().map(PlatTableVO::getTableName).collect(
                Collectors.toList()).toString();
        String subTableName = tableNames.substring(1, tableNames.length() - 1);
        //拿到所有的内容数据
        DataReturn tableInfoByTableName = disposeFeignClient.selectTableInfoByTableName(subTableName, districtCode);
        if (!ResultCode.SUCCESS.getCode().equals(tableInfoByTableName.getCode())
                && !FireConstant.ALARMS_SUCCESS_CODE.equals(tableInfoByTableName.getCode())) {
            throw new ForestBaseException(tableInfoByTableName.getErrorMsg());
        }
        //
        List<Map> tableInfoMaps = JSON.parseArray(JSON.toJSONString(tableInfoByTableName.getData()), Map.class);
        //拿到数据匹配经纬度 和半径
        for (PlatTableVO platTableVO : platTableVOList) {
            for (Map map : tableInfoMaps) {
                List<Map> mapList = (List<Map>) map.get(platTableVO.getTableName());
                //拿到表数据去对比数据
                if (!CollectionUtil.isEmpty(mapList)) {
                    List<FireSituationVO> mapInfoList = checkData(platTableVO.getIconImg(), mapList,
                            platTableVO.getName(), platTableVO.getId(), platTableVO.getCode(),
                            platTableVO.getTableName(), longitude, latitude, radius);
                    //                if (!CollectionUtil.isEmpty(mapInfoList)) {
                    resultMap.put(platTableVO.getCode(), mapInfoList);
                }
            }
            //       }
        }
        return resultMap;
    }

    private List<FireSituationVO> checkData(String iconImg, List<Map> mapList, String name, String tableId,
                                            String tableName, String code, String longitude, String latitude,
                                            String radius) {
        List<FireSituationVO> fireSituationVOList = new ArrayList<>();
        for (Map map : mapList) {
            if (map.containsKey("longitude") && map.containsKey("latitude")
                    && StrUtil.isNotEmpty(MapUtil.getStr(map, "longitude")) && StrUtil.isNotEmpty(
                    MapUtil.getStr(map, "latitude"))) {
                double longitudeT = Double.parseDouble(map.get("longitude").toString());
                double latitudeT = Double.parseDouble(map.get("latitude").toString());
                //转数据
                //查询经纬度范围
                double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude),
                        longitudeT, latitudeT);
                if (distance <= Double.parseDouble(radius)) {
                    FireSituationVO fireSituationVO = getFireSituationVO(iconImg, name, tableId, tableName, code, map);
                    fireSituationVOList.add(fireSituationVO);
                }
            }

        }
        //处理返回数据
        return fireSituationVOList;
    }


    @Override
    public Map<String, List> getSimplePeopleList(String flag) {


        return null;
    }


    /**
     * 火场态势周围人员设备查询（无人机、视频监控、护林员）
     *
     * @param longitude
     * @param latitude
     * @param radius
     *
     * @return
     */
    @Override
    public Map<String, List> getPeopleEquNearbyRadius(String longitude, String latitude, String radius, String flag) {
        Map<String, List> resultMap = new HashMap<>();
        //是否处于指挥调度中
        String districtCode = "";
        if (StrUtil.isEmpty(flag)) {
            districtCode = JwtTokenUtils.getDistrictCode();
        }
        //查询无人机相关资源
//        DataReturn dataReturn = uavFeignClient.querySimpleDataByCondition(radius, longitude, latitude, flag);
//        if (dataReturn.getData() != null && "00000".equals(dataReturn.getCode())) {
//            String jsonObject = JSON.toJSON(dataReturn.getData()).toString();
//            List<Map<String, Object>> uavAllList = JSONArray.parseObject(jsonObject, List.class);
//            if (!CollectionUtils.isEmpty(uavAllList)) {
//                if (!CollectionUtils.isEmpty(uavAllList)) {
//                    resultMap.put("uavDataList", uavAllList);
//                }
//            }
//        }
        //查询视频监控相关资源
        //视频监控
        List<CameraVO> commCameraInfoDtoList = cameraInfoService.getCameraPosition(districtCode);
        List<CameraVO> cameraVOList = new ArrayList<>();
        commCameraInfoDtoList.forEach(cameraVO -> {
            double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude),
                    new Double(cameraVO.getLongitude()), new Double(cameraVO.getLatitude()));
            if (distance <= Double.parseDouble(radius)) {
                cameraVOList.add(cameraVO);
            }
        });

        if (!CollectionUtils.isEmpty(cameraVOList)) {
            resultMap.put("videoMonitorDataList", cameraVOList);
        }

        //查询护林员相关资源
        //护林员
        List<ForesterDTO> foresterDTOList = foresterService.foresterSelect(null, null, null, null, null, null, null);
        List<ForesterDTO> foresterResultList = new ArrayList<>();
        for (ForesterDTO foresterDTO : foresterDTOList) {
            if (StringUtils.isNotBlank(foresterDTO.getLongitude()) && StringUtils.isNotBlank(
                    foresterDTO.getLatitude())) {
                double distance = GeoUtils.GetDistanceTwo(Double.parseDouble(longitude), Double.parseDouble(latitude),
                        new Double(foresterDTO.getLongitude()), new Double(foresterDTO.getLatitude()));
                if (distance <= Double.parseDouble(radius)) {
                    foresterResultList.add(foresterDTO);
                }
            }
        }
        if (!CollectionUtils.isEmpty(foresterResultList)) {
            resultMap.put("foresterDataList", foresterResultList);
        }
        return resultMap;
    }

    @Override
    public List<FireResourceVO> getFireTotal() {
        List<FireResourceVO> resultList = new ArrayList<>();
        return resultList;
    }


    private FireSituationVO getFireSituationVO(String iconImg, String name, String tableId, String tableName,
                                               String code, Map map) {
        FireSituationVO fireSituationVO = new FireSituationVO();
        if (Objects.nonNull(map.get("longitude"))) {
            fireSituationVO.setLongitude(map.get("longitude").toString());
        }
        if (Objects.nonNull(map.get("latitude"))) {
            fireSituationVO.setLatitude(map.get("latitude").toString());
        }
        if (Objects.nonNull(map.get("id"))) {
            fireSituationVO.setId(map.get("id").toString());
        }
        if (Objects.nonNull(map.get("flag"))) {
            fireSituationVO.setFlag(Integer.parseInt(map.get("flag").toString()));
        }
//        fireSituationVO.setLongitude(map.get("longitude").toString());
//        fireSituationVO.setLatitude(map.get("latitude").toString());
//        fireSituationVO.setId(map.get("id").toString());
//        fireSituationVO.setFlag(Integer.parseInt(map.get("flag").toString()));
        if (Objects.nonNull(map.get("isOnline"))) {
            fireSituationVO.setIsOnline(Integer.parseInt(map.get("isOnline").toString()));
        }
        fireSituationVO.setName(name);
        fireSituationVO.setIconImg(iconImg);
        fireSituationVO.setResourceLayerName(tableId);
        fireSituationVO.setTableName(tableName);
        fireSituationVO.setTableId(tableId);
        if (Objects.nonNull(map.get("name"))) {
            fireSituationVO.setOtherName(map.get("name").toString());
        }
        //根据tableId查询icon
        // disposeFeignClient.select
        return fireSituationVO;
    }

}
